package interceptor

import (
	"context"
	selfConst "git.multiverse.io/eventkit/dxc-server/constant"
	"git.multiverse.io/eventkit/dxc-server/models"
	"git.multiverse.io/eventkit/kit/constant"
	"git.multiverse.io/eventkit/kit/contexts"
	frameConsts "git.multiverse.io/framework/common/constant"
	"git.multiverse.io/framework/common/msg"
	"git.multiverse.io/framework/log"
	"strconv"
)

type Interceptor struct{}

func (l *Interceptor) PreHandle(ctx context.Context, request *msg.Message) error {
	handlerContexts := contexts.HandlerContextsFromContext(ctx)

	traceID := ""
	spanID := ""
	parentSpanID := ""
	timeoutMilliseconds := 0

	org := ""
	az := ""
	su := ""
	instanceId := ""
	environment := ""
	workspace := ""
	nodeId := ""

	if request != nil {
		traceID, _ = request.GetAppProperty(frameConsts.KeyTraceID)
		spanID, _ = request.GetAppProperty(frameConsts.KeySpanID)
		parentSpanID, _ = request.GetAppProperty(frameConsts.KeyParentSpanID)
		timeoutMillisecondsStr, _ := request.GetAppProperty(frameConsts.To3)
		if "" != timeoutMillisecondsStr {
			timeout, err := strconv.Atoi(timeoutMillisecondsStr)
			if err == nil {
				timeoutMilliseconds = timeout
			}
		}

		org = request.GetSourceORG()
		az = request.GetSourceAZ()
		su = request.GetSourceSU()
		if su == "" {
			su = request.GetSourceDCN()
		}
		instanceId = request.GetSourceInstanceID()
		environment = request.GetSourceENV()
		workspace = request.GetSourceWKS()
		nodeId = request.GetSourceNodeID()
	}

	if 0 == timeoutMilliseconds {
		timeoutMilliseconds = constant.DefaultTimeoutMilliseconds
	}

	spanCtx := contexts.BuildSpanContexts(
		contexts.TraceID(traceID),
		contexts.SpanID(spanID),
		contexts.ParentSpanID(parentSpanID),
		contexts.TimeoutMilliseconds(timeoutMilliseconds),
	)

	dxcContext := &models.DxcContext{
		SrcOrg:         org,
		SrcAz:          az,
		SrcSu:          su,
		SrcInstanceId:  instanceId,
		SrcEnvironment: environment,
		SrcNodeId:      nodeId,
		SrcWorkspace:   workspace,
		SpanCtx:        spanCtx,
	}

	log.Debugsf("Interceptor build dxcContext:[%++v], spanCtx:[%++v]", dxcContext, *spanCtx)

	handlerContexts.AppendAttach(selfConst.DXC_CONTEXT_KEY, dxcContext)
	return nil
}

func (l *Interceptor) PostHandle(ctx context.Context, request *msg.Message, response *msg.Message) error {
	// DO NOTHING
	return nil
}
